const config = require('config')
import {findUsers,registerUser,resetUserPasswd,deleteUser,editUser,getUser,addOrUpdateContact} from '../utils/nc/user'
import {addShareLink,getShareByPath} from "../utils/nc/share"
const sharePath = config.get('nextcloud.share_path')
const {createClient} = require("webdav")
const nextcloud = config.get('nextcloud')

const exist = async (id) =>{
    let users = await findUsers()
    return users.some((userid)=>{
        return userid==id
    })
}

const addShareFolder = async(user)=>{
    let client = createClient(
        `${nextcloud.host}/remote.php/dav/files/${user.id}`,
        {username: user.id, password: user.passwd}
    );
    await client.createDirectory(sharePath)
}


const register = async (user) => {
    await registerUser(user)
    await addShareFolder(user)
    let result = await addShareLink(user, sharePath)
    user.shareLink = result.url
    await addOrUpdateContact(user)
}


module.exports = {
    register,
    resetUserPasswd,
    exist,
    getShareByPath,
    deleteUser,
    editUser,
    getUser
}
